package com.xs.batch.bad;

import com.xs.batch.entity.Order;
import com.xs.batch.enums.OrderStatus;
import com.xs.batch.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class BadBatch {

    @Autowired
    OrderRepository orderRepository;


   void  batchProcessor(){
       Page<Order> orderPage;
       int pageSize = 10000;
       int page = 0;
       do {
           // 查询超过24小时未支付订单
           orderPage = orderRepository.findByStatusAndCreatedAtBefore(
                   OrderStatus.CREATED.toString(),
                   LocalDateTime.now().minusHours(24),
                   PageRequest.of(page, pageSize)
           );

           for (Order order : orderPage) {
               order.setStatus(OrderStatus.CLOSED.toString());
               orderRepository.save(order);
           }
           page++;
       } while (orderPage.hasNext());
    }
}
